package com.wordpress.hybrid.util;

import android.os.Build;
import android.util.Log;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

final class HttpConnectionHelper {

    static final String TAG = "HttpConnectionHelper";

    private static final String HEAD_CONTENT_LEN = "content-length";
    private static final String HEAD_USER_AGENT = "User-agent";

    private static final int HTTP_CONNECTION_TIMEOUT_MS = 8 * 1000;
    private static final int HTTP_SO_TIMEOUT_MS = 15 * 1000;

    // for M4: MiuiMusic/4.4.4 (Linux; U; Android 4.4.4; MI 4LTE Build/KTU84P)
    public static String USER_AGENT = "MiuiMusic/" + Build.VERSION.RELEASE +
            " (Linux; U; Android " + Build.VERSION.RELEASE + "; " + Build.MODEL + " Build/" + Build.ID + ")";

    private static class ConnectionInputStream extends FilterInputStream {

        private final HttpURLConnection mConnection;

        ConnectionInputStream(InputStream in, HttpURLConnection conn) {
            super(in);
            mConnection = conn;
        }

        @Override
        public void close() throws IOException {
            try {
                super.close();
            } catch (ArrayIndexOutOfBoundsException e) {
                Log.e(TAG, e.toString());
            } finally {
                mConnection.disconnect();
            }
        }
    }

    public static HttpURLConnection openURL(String url) throws MalformedURLException, IOException {
        return openURL(new URL(url));
    }

    public static HttpURLConnection openURL(URL url) throws IOException {
        if (!NetworkUtil.isNetworkAllow()) {
            throw new IOException("Network is disallow!");
        }
        Log.d(TAG, "open url=" + url);
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(HTTP_CONNECTION_TIMEOUT_MS);
        conn.setReadTimeout(HTTP_SO_TIMEOUT_MS);
        conn.addRequestProperty(HEAD_USER_AGENT, USER_AGENT);
        return conn;
    }

    public static InputStream wrap(InputStream in, HttpURLConnection conn) {
        return new ConnectionInputStream(in, conn);
    }

    public static long getTime(InputStream in) {
        if (in instanceof ConnectionInputStream) {
            return ((ConnectionInputStream) in).mConnection.getDate();
        }

        return -1;
    }

    public static long getContentLength(HttpURLConnection conn) {
        return SecurityGuardian.getHeaderField(conn, HttpConnectionHelper.HEAD_CONTENT_LEN);
    }
}

